<template>

  <div class="orderingplan flex flex-col">
    <!-- 查询区 -->
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :model="priceupdatesFrom" label-width="auto" inline @keyup.enter="searchFn">
        <el-form-item label="创建时间：">
          <el-date-picker v-model="value1" type="daterange" range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" @change="timeChangeFn" />
        </el-form-item>
        <el-form-item label="订货方案名称">
          <pb-input v-model="priceupdatesFrom.orderPlanName" />
        </el-form-item>
        <el-form-item label="状态：">
          <pb-check :list="classList" @change="changeCheck($event)"></pb-check>
        </el-form-item>
      </el-form>
    </searchCard>

    <!-- 表格区 -->
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <div class="content-box">
          <ContentOperation>
            <pb-button v-hasPerm="'center:orderingplan:add'" size="small" plain class="mr-6" @click="onaddVisibleFn">
              +添加
            </pb-button>
          </ContentOperation>
          <div class=" main-box ">
            <pb-table :column="planColumn" :tableData="purchasingSupplyData" :bottomElement="['pb-page']"
              :indexWidth="60">
              <template #enableStatus="{ row }">
                <div class="statusbox">
                  <span class="radius"
                    :style="{ 'background-color': getsupplyStatustextcolorFn(row.enableStatus, 'color') }"></span><span>{{
                      getsupplyStatustextcolorFn(row.enableStatus, 'text') }}</span>
                </div>
              </template>
              <template #supplyTenant="{ row }">
                <div class=" flex justify-center ">

                  <el-popover placement="top" :width="200" trigger="hover" :content="row.supplyTenant">
                    <template #reference>
                      <div class="popContent pb-ellipsis">
                        {{ row.supplyTenant }}
                      </div>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #remark="{ row }">
                <div class=" flex justify-center ">

                  <el-popover placement="bottom" :width="200" trigger="hover" :content="row.remark">
                    <template #reference>
                      <div class="popContent pb-ellipsis">
                        {{ row.remark }}
                      </div>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #operate="{ row }">
                <!-- <pb-button text size="small" @click="offAddpurchaasingFn(row)">启用</pb-button> -->
                <span v-hasPerm="'center:orderingplan:switch'">
                  <PopconfirmButton @confirm="EnableFn(row)" v-if="row.enableStatus != 1" text="启用"></PopconfirmButton>
                  <PopconfirmButton @confirm="EndbleFn(row)" v-if="row.enableStatus == 1" text="禁用"></PopconfirmButton>
                  <p class="divider mr-2 ml-2" v-if="row.enableStatus != 1"></p>
                  <p class="divider mr-2 ml-2" v-if="row.enableStatus == 1"></p>
                </span>
                <span v-hasPerm="'center:orderingplan:edit'">
                  <pb-button text size="small" @click="onEditFn(row, 'updata')">编辑</pb-button>
                  <p class="divider mr-2 ml-2"></p>
                </span>
                <span v-hasPerm="'center:orderingplan:view'">
                  <pb-button text size="small" @click="onEditFn(row, 'detail')">查看</pb-button>
                  <p class="divider mr-2 ml-2" v-if="row.enableStatus != 1"></p>
                </span>
                <span v-hasPerm="'center:orderingplan:delete'">
                  <PopconfirmButton v-if="row.enableStatus != 1" @confirm="deleteFn(row)"></PopconfirmButton>
                </span>
                <!-- <p class="divider mr-2 ml-2" v-if="row.enableStatus != 1"></p> -->
                <!-- <pb-button text size="small" @click="offAddpurchaasingFn(row)">导出</pb-button> -->
              </template>
            </pb-table>
            <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
              @onChange="onPagesChange" :total="pages.total"></pb-pagination>
          </div>
        </div>

      </pb-card>
    </div>
    <Viewdetail :isVisible="isVisible" :detailFrom="detailFrom" @offisVisibleFn="offisVisibleFn" />
    <Addprice :addVisible="addVisible" :SupplierList="SupplierList" @canceladdisVisibleFn="canceladdisVisibleFn"
      @confirmaddVisibleFn="confirmaddVisibleFn" />
    <Edit ref="refEdit" @GetOrderListFn="GetOrderListFn"></Edit>
  </div>
</template>

<script setup lang="ts">
import Viewdetail from './components/viewdetail.vue'
import Addprice from './components/addprice.vue'
import Edit from './components/edit.vue'
import { createMsgBox } from '@/Public-UIlibrary/pb-message-box/method';
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
import { GetPurchaseListApi, DetetePurchaseSupplyApi, ExportSkuSupplyBlodApi, GetOrderPlanPageApi, EnableOrderPlanApi, disabledOrderPlanApi, DeleteOrderPlanApi } from '@/api/Purchasing'
import { formattedDate } from '@/utils/moment'
const EnableFn = (row: any) => {
  // EnablePurchaseSupplyApi({ skuSupplyId: row.skuSupplyId }).then(res => {
  //   if (res.code == 2000) {
  //     getPurchaseSkuSupplyListApifn()
  //   } else if (res.code == 5002) {
  //     createMsgBox(
  //       res.msg,
  //       { cancelText: '取消', showTitleIcon: false, confirmText: '确认', title: '错误提示', Width: 500, connectList: res.data, showIcon: false }).then(res => {
  //         if (res) {
  //           // getPurchasePlanApi(1)
  //         } else {
  //           // showPopup.value = false
  //         }
  //       })
  //   }
  // })
  EnableOrderPlanApi({
    orderPlanId: row.orderPlanId
  }).then(res => {
    if (res.code == 2000) {
      createMessage({
        message: '启用成功'
      })
      getPurchaseSkuSupplyListApifn()
    } else if (res.code == 5002) {
      createMsgBox(
        res.msg,
        { cancelText: '取消', showTitleIcon: false, confirmText: '确认', title: '错误提示', Width: 500, connectList: res.data, showIcon: false }).then(res => {
          if (res) {
            // getPurchasePlanApi(1)
          } else {
            // showPopup.value = false
          }
        })
    }
  })
}
const refEdit = ref(null as any)
const onEditFn = (row: any, status: string) => {
  row.status = status
  refEdit.value.show(row)
}
const GetOrderListFn = () => {

}
const EndbleFn = (row: any) => {
  disabledOrderPlanApi({ orderPlanId: row.orderPlanId }).then(res => {
    if (res.code == 2000) {
      createMessage({
        message: '禁用成功'
      })
      getPurchaseSkuSupplyListApifn()
    }
  })
}
const deleteFn = (row: any) => {
  DeleteOrderPlanApi({ orderPlanId: row.orderPlanId }).then(res => {
    if (res.code == 2000) {
      getPurchaseSkuSupplyListApifn()
    }
  })
}
const kitchenList = ref([])
const planColumn = reactive([
  {
    key: 'orderPlanNo',
    name: '方案编号'
  },
  {
    key: "orderPlanName",
    name: "订货方案名称",
  },
  {
    slot: "enableStatus",
    name: "状态",
  },
  {
    slot: "supplyTenant",
    name: "适用单位",
  },
  {
    key: 'createTime',
    name: "创建时间",
  }, {
    key: 'creator',
    name: "创建人",
  }, {
    slot: 'remark',
    name: "备注",
  },
  {
    width: 180,
    slot: "operate",
    name: "操作",
    fixed: 'right',
  },
])
const detailFrom = reactive({

})
const value1 = ref('')
const addpurchaseing = ref(null) as any
const purchasingSupplyData = ref([])
const offAddpurchaasingFn = (row: any) => {
  // console.log('row', row)
  // addpurchaseing.value.showFn(row ? JSON.parse(JSON.stringify(row)) : '')
  ExportSkuSupplyBlodApi({
    skuSupplyId: row.skuSupplyId
  }).then((response: any) => {
    const disposition = response.headers['content-disposition'];
    // const filenameMatch = disposition.match(/filename*=utf-8''\s*([^;]+)/); 没用的东西
    const parts = disposition.split("filename*=utf-8''"); // 注意这里的分割字符串，它包含了一个空的单引号来匹配格式
    const encodedFilenamePart = parts[1] ? parts[1].split(';')[0] : null; // 分割出可能包含文件名的部分，并截取到下一个分号之前
    let decodedFilename = ''
    if (encodedFilenamePart) {
      // 解码文件名
      decodedFilename = decodeURIComponent(encodedFilenamePart);
      decodedFilename = decodedFilename.replace(/\(.*?\)/, '');
      // 输出解码后的文件名
      console.log("Decoded filename:", decodedFilename);
    } else {
      decodedFilename = "物价更新" + new Date().getTime() + '.xlsx'
      // 如果没有找到包含文件名的部分，输出警告信息
      // console.warn("No filename part found in the Content-Disposition header using the simplified method.");
    }
    let blob = new Blob([response.data]);
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    // console.log(href, '22href')
    downloadElement.href = href;
    downloadElement.download = decodedFilename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}
const getsupplyStatustextcolorFn = (status: any, type: string) => {
  if (type == 'text') {
    if (status == 1) {
      return '已启用'
    } else if (status == 2) {
      return '已禁用'
    } else {
      return '未启用'
    }
  } else {
    if (status == 1) {
      return '#09B562'
    } else if (status == 2) {
      return 'rgba(0,0,0,0.25)'
    } else {
      return '#F52F3E'
    }
  }
}
const timeChangeFn = (time: any) => {
  priceupdatesFrom.startDate = formattedDate(time[0], 'YYYY-MM-DD')
  priceupdatesFrom.endDate = formattedDate(time[1], 'YYYY-MM-DD')
}
const classList = ref([
  { label: '全部', val: null, checked: true },
  { label: '已启用', val: 1, checked: false },
  { label: '已禁用', val: 2, checked: false },
  { label: '未启用', val: 0, checked: false },
])
const changeCheck = (eve: any) => {
  // console.log(eve, '22')
  priceupdatesFrom.enableStatus = eve.val
  getPurchaseSkuSupplyListApifn()
}
const priceupdatesFrom = reactive({
  startDate: "",
  endDate: "",
  enableStatus: "",
  orderPlanName: ''
})
const pageInit = () => ({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const pages = ref(pageInit());
const onPagesChange = () => {
  getPurchaseSkuSupplyListApifn()
}

const searchFn = () => {
  getPurchaseSkuSupplyListApifn()
}
const resetFn = () => {
  // console.log(value1.value)
  clearObjKey(priceupdatesFrom)
  value1.value = ''
  classList.value.map(el => {
    el.checked = false
  })
  classList.value[0].checked = true
  getPurchaseSkuSupplyListApifn()
}
const getPurchaseSkuSupplyListApifn = () => {
  // GetOrderPlanPageApi
  GetOrderPlanPageApi({
    "currentPage": pages.value.currentPage,
    "pageSize": pages.value.pageSize,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "startDate": priceupdatesFrom.startDate,
    "endDate": priceupdatesFrom.endDate,
    "orderPlanName": priceupdatesFrom.orderPlanName,
    "enableStatus": priceupdatesFrom.enableStatus

  }).then(res => {
    purchasingSupplyData.value = res.data.records ? res.data.records : []
    pages.value.total = res.data.total
  })
}
const clearObjKey = (clearForm: any) => {
  Object.keys(clearForm).forEach((key: any) => {
    if (Array.isArray(clearForm[key])) {
      // 如果属性是数组，则清空数组
      clearForm[key].length = 0;
    } else {
      // 如果属性不是数组，则设置为默认值（默认为空字符串）
      clearForm[key] = '';
    }
  });
}
const addVisible = ref(false)
const onaddVisibleFn = () => {
  addVisible.value = true
}
const confirmaddVisibleFn = () => {
  addVisible.value = false
  getPurchaseSkuSupplyListApifn()
}
const canceladdisVisibleFn = () => {
  addVisible.value = false
}
const isVisible = ref(false)
const ondetailviewFn = (row: any) => {
  clearObjKey(detailFrom)
  Object.assign(detailFrom, row)
  isVisible.value = true
}
const offisVisibleFn = () => {
  isVisible.value = false
}
const SupplierList = ref([] as any)
onMounted(() => {
  getPurchaseSkuSupplyListApifn()
  GetPurchaseListApi({ "pageSize": -1, }).then(res => {
    SupplierList.value = res.data.records
  })
})
</script>

<style lang="scss" scoped>
.content-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.main-box {
  padding: 16px;
  box-sizing: border-box;
}

.orderingplan {
  .statusbox {
    display: flex;
    align-items: center;

    .radius {
      width: 6px;
      height: 6px;
      // background: red;
      display: inline-block;
      margin-right: 4px;
      border-radius: 10px;
    }
  }
}

.popContent {
  width: 100%;
  overflow: hidden;
}
</style>